import React, { useEffect, useRef, forwardRef, useImperativeHandle, useState } from 'react'
import Mescroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
import { debounce } from 'yjr-utils'

export interface instanceType {
  // 结束下拉刷新和上拉加载的状态,
  endSuccess: (length?: number, hasMore?: boolean) => void
  // 滚动列表到指定位置,time为毫秒
  scrollTo: (yAxis: number, time: number) => void
  // 销毁实例
  destroy: () => void
}
export interface refType {
  // 结束下拉刷新状态
  endDropDown: () => void
  // 结束上拉加载状态: hasMore是否有更多,传false时上滑触底回调不再触发
  endUpGlide: (hasMore?: boolean) => void
  // 滚动列表到指定位置: yAxis为竖直方向距离  time为毫秒
  scrollTo: (yAxis: number, time: number) => void
}

interface PropRule {
  // 下拉刷新回调
  dropDownCb?: () => void
  // 上滑触底回调
  upGlideCb?: () => void
  className?: string
  style?: React.CSSProperties
  children?: React.ReactNode
  // 还剩多少距离(px)触发上滑触底回调
  upGlideOffset?: number
}
function MescrollReact(
  {
    dropDownCb = () => {},
    upGlideCb = () => {},
    className,
    style,
    children,
    upGlideOffset = 100
  }: PropRule,
  ref: React.ForwardedRef<refType>
): JSX.Element {
  const dom = useRef<HTMLDivElement>(null)
  const instance = useRef<instanceType | null>(null)
  const [tog, setTog] = useState(false)
  useEffect(() => {
    instance.current = new Mescroll(dom.current, {
      down: {
        // 必须在顶部才可以下拉刷新
        mustToTop: false,
        // 关闭上来就自动执行一次
        auto: false,
        // 不允许ios的bounce回弹
        isBounce: false,
        callback: debounce(dropDownCb, 500)
      },
      up: {
        auto: false,
        isBounce: false,
        offset: upGlideOffset,
        callback: debounce(upGlideCb, 500),
        htmlNodata: `<p class="upwarp-nodata">到底了～～ </p>`
      }
    })
    setTog(true)
    return () => instance.current?.destroy()
  }, [])
  useImperativeHandle<refType, refType>(
    ref,
    () => {
      const tg = instance.current
      return {
        endDropDown: () => tg?.endSuccess(),
        endUpGlide: (hasMore = true) => tg?.endSuccess(10, hasMore),
        scrollTo: (yAxis, time) => tg?.scrollTo(yAxis, time)
      }
    },
    [tog]
  )
  return (
    <div ref={dom} className={className?.concat(' mescroll')} style={style}>
      <div>{children}</div>
    </div>
  )
}

export default forwardRef(MescrollReact)
